<template>
    <div class="white-box">
        <el-form ref="ruleRef" :model="ruleForm" :rules="ruleCheck" label-width="120px">
            <el-form-item label="商品分类" prop="class_id" required>
                <el-select v-model="ruleForm.class_id" placeholder="请选择商品分类">
                    <el-option :label="item.title" :value="item.cate_id" v-for="item in pub_options.cate_list" :key="item.title" />
                </el-select>
            </el-form-item>
            <el-form-item label="商品名称" prop="good_name">
                <el-input v-model.trim="ruleForm.good_name" clearable placeholder="请输入商品名称" />
            </el-form-item>
            <el-form-item label="商品封面图" prop="img_paths" required>
                <div class="img-box flexs-center" @click.stop="showImg = true" v-if="ruleForm.img_paths == ''">
                    <el-icon color="#999" size="26px">
                        <UploadFilled />
                    </el-icon>
                </div>
                <div class="img-selects" v-else>
                    <el-image class="img-selects__pic" :src="proxy.imgUrl + ruleForm.img_paths + '!img_400'" :preview-src-list="srcList" fit="cover" />
                    <div class="img-del" @click.stop="delImg">
                        <el-icon size="14px" color="#fff"><CloseBold /></el-icon>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="颜色分类" prop="colors_id" required>
                <el-select v-model="ruleForm.colors_id" placeholder="请选择颜色分类">
                    <el-option :label="item.title" :value="item.color_id" v-for="item in pub_options.color_list" :key="item.color_id" />
                </el-select>
            </el-form-item>
            <el-form-item label="商品规格">
                <el-form-item prop="norm">
                    <el-input v-model.trim="ruleForm.norm" clearable placeholder="请输入商品规格" />
                </el-form-item>
                <el-form-item prop="unit" style="margin-left: 12px">
                    <el-input style="width: 80px" v-model.trim="ruleForm.unit" clearable placeholder="商品单位" />
                </el-form-item>
            </el-form-item>
            <el-form-item label="排序" prop="sort">
                <el-input v-model.trim="ruleForm.sort" oninput="value=value.replace(/[^\d]/g,'')" clearable placeholder="请输入排序" />
                <div class="input-tips">一个好的排序能让您更加方便管理商品</div>
            </el-form-item>
            <!-- <el-form-item label="运费类型" prop="freight_type" required>
                <el-radio-group v-model="ruleForm.freight_type">
                    <el-radio label="0">统一运费</el-radio>
                    <el-radio label="1">运费模板</el-radio>
                </el-radio-group>
            </el-form-item> -->
            <!-- <el-form-item label="统一运费" prop="unified_freight" v-if="ruleForm.freight_type == 0">
                <el-input v-model.trim="ruleForm.unified_freight" clearable placeholder="请输入统一运费" oninput="value=value.replace(/[^\d.]/g,'')" />
            </el-form-item> -->
            <el-form-item label="运费模板" prop="template_id" required>
                <el-select v-model="ruleForm.template_id" placeholder="请选择运费模板">
                    <el-option :label="item.title" :value="item.express_id" v-for="item in pub_options.express_list" :key="item.express_id" />
                </el-select>
            </el-form-item>
            <el-form-item label="商品等级" prop="level_data">
                <el-button color="#4B93FA" plain :icon="Plus" @click="clickLevelAdd"> 添加等级 </el-button>
                <div class="level-table">
                    <el-table
                        v-loading="loading"
                        :data="ruleForm.level_data"
                        :header-cell-style="{ background: '#F5F7FA' }"
                        element-loading-background="rgba(255, 255, 255, 0.6)"
                    >
                        <el-table-column label="商品等级" min-width="400">
                            <template #default="{ row }">
                                <el-select v-model="row.level_id" placeholder="请选择商品等级" @change="changeVal">
                                    <el-option
                                        :label="item.level_name"
                                        :value="item.level_id"
                                        v-for="item in pub_options.leave_list"
                                        :key="item.level_id"
                                        :disabled="item.disabled"
                                        :hidden="item.disabled"
                                    />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column label="重量(kg)" min-width="360">
                            <template #default="{ row }">
                                <el-input
                                    v-model="row.weight"
                                    clearable
                                    style="width: 240px"
                                    oninput="value=value.replace(/[^\d.]/g,'')"
                                    placeholder="请输入重量"
                                />
                            </template>
                        </el-table-column>
                        <el-table-column label="体积(m³)" min-width="360">
                            <template #default="{ row }">
                                <el-input
                                    style="width: 240px"
                                    v-model="row.volume"
                                    clearable
                                    oninput="value=value.replace(/[^\d.]/g,'')"
                                    placeholder="请输入体积"
                                />
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="180" class-name="operation-nav" fixed="right">
                            <template #default="scope">
                                <el-button link type="primary" @click="clickAdd(scope.row)" v-if="type == 2"> 保存 </el-button>
                                <el-button link type="primary" @click="clickDel(scope.row, scope.$index)"> 删除 </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="input-tips">
                    <code>当编辑商品时</code>修改等级信息后，请先点击右侧<code>保存</code>按钮，然后再点击下方的<code>确认保存</code>按钮。以免出现未更新情况
                </div>
            </el-form-item>
            <el-form-item>
                <div class="flexs" style="margin-top: 30px">
                    <el-popconfirm title="修改/添加等级时请先点击右侧保存按钮哦！" width="220" confirm-button-text="确定" cancel-button-text="取消" @confirm="submitForm(ruleRef)" v-if="type == 2">
                        <template #reference>
                            <el-button color="#4B93FA" style="color: #fff" size="large" :loading="form_loading"> 确认保存 </el-button>
                        </template>
                    </el-popconfirm>
                    <el-button color="#4B93FA" style="color: #fff" size="large" :loading="form_loading" @click="submitForm(ruleRef)" v-else> 确认保存 </el-button>
                    <el-button size="large" @click="resetForm(ruleRef)">重置</el-button>
                </div>
            </el-form-item>
        </el-form>

        <!-- 图片库 -->
        <picture-library :show="showImg" :select_multiple="false" @close="showImg = false" @select="selectImg"> </picture-library>

        <go-back />
    </div>
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, reactive } from "vue"
import { useRouter, useRoute } from "vue-router"
import { UploadFilled, Plus, CloseBold } from "@element-plus/icons-vue"
import PictureLibrary from "@components/PictureLibrary.vue"
import GoBack from "@components/GoBack.vue"

const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()

let gid = route.query.gid || ""
let type = route.query.type || 1 // 1是添加，2是编辑
onMounted(() => {
    pubClass()
    gid && getDetail()
})

function getDetail() {
    loading.value = true
    proxy.$axios
        .get("product/common/update", {
            params: {
                product_common_id: gid,
            },
        })
        .then((res) => {
            loading.value = false
            if (res.data.code == 0) {
                let result = res.data.data
                ruleForm.class_id = result.cate_id
                ruleForm.colors_id = result.color_id
                ruleForm.good_name = result.product_name
                ruleForm.norm = result.norm
                ruleForm.unit = result.unit
                ruleForm.sort = result.order_by
                // ruleForm.freight_type = result.freight_type || "1"
                // ruleForm.unified_freight = result.freight || ""
                ruleForm.template_id = result.express_id || ""
                ruleForm.level_data = result.product_levels
                ruleForm.img_paths = result.product_img
                result.product_levels.forEach((item) => {
                    let indexs = pub_options.value.leave_list.findIndex((sub) => sub.level_id == item.level_id)
                    if (indexs > -1) {
                        pub_options.value.leave_list[indexs].disabled = true
                    }
                })
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {
            loading.value = false
        })
}

/**
 * 添加/编辑
 * @property {Boolean} form_loading 提交按钮状态
 * @property {Array} ruleColorRef 表单规则
 * @property {Object} ruleColorForm  表单字段
 * @property {Object} ruleCheckColor  表单提示
 * @property {Function} submitColorForm 提交表单
 */
const form_loading = ref(false)
const ruleRef = ref(null)
const ruleForm = reactive({
    class_id: "",
    colors_id: "",
    good_name: "",
    norm: "",
    unit: "扎",
    freight_type: "1",
    unified_freight: "",
    template_id: "",
    img_paths: "",
    level_data: [],
    sort: "100",
})
// validNumOrPoint
const ruleCheck = reactive({
    class_id: [{ required: true, message: "请选择商品分类", trigger: "change" }],
    colors_id: [{ required: true, message: "请选择商品颜色", trigger: "change" }],
    good_name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
    norm: [{ required: true, message: "请输入商品规格", trigger: "blur" }],
    unit: [{ required: true, message: "请输入商品单位", trigger: "blur" }],
    freight_type: [{ required: true, message: "请选择运费类型", trigger: "blur" }],
    level_data: [{ type: "array", required: true, message: "请添加商品等级", trigger: "change" }],
    template_id: [{ required: true, message: "请选择运费模板", trigger: "change" }],
    img_paths: [{ required: true, message: "请选择商品封面图", trigger: "change" }],
    sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
})
const submitForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            // let regu = /^\d+(\.\d{1,2})?$/
            let regum = /^\d+(\.\d{1,3})?$/
            // if (ruleForm.freight_type == 0 && ruleForm.unified_freight == "") {
            //     proxy.$message({ message: "请输入统一运费", type: "warning" })
            //     return
            // }
            // if (ruleForm.freight_type == 0 && !regum.test(ruleForm.unified_freight)) {
            //     proxy.$message({ message: "格式为整数或小数(保留三位小数)", type: "warning" })
            //     return
            // }
            // if (ruleForm.freight_type == 1 && ruleForm.template_id == "") {
            //     proxy.$message({ message: "请选择运费模板", type: "warning" })
            //     return
            // }
            for (let i = 0; i < ruleForm.level_data.length; i++) {
                if (ruleForm.level_data[i].level_id == "") {
                    proxy.$message({ message: "请完善商品等级", type: "warning" })
                    return
                }
                if (!regum.test(ruleForm.level_data[i].weight)) {
                    proxy.$message({ message: "重量输入有误", type: "warning" })
                    return
                }
                if (!regum.test(ruleForm.level_data[i].volume)) {
                    proxy.$message({ message: "体积输入有误", type: "warning" })
                    return
                }
                ruleForm.level_data[i].volume = ruleForm.level_data[i].volume ? ruleForm.level_data[i].volume : 0
            }
            form_loading.value = true
            let data = {
                cate_id: ruleForm.class_id,
                product_name: ruleForm.good_name,
                color_id: ruleForm.colors_id,
                norm: ruleForm.norm,
                unit: ruleForm.unit,
                freight_type: ruleForm.freight_type,
                // freight: ruleForm.unified_freight,
                express_id: ruleForm.template_id,
                product_img: ruleForm.img_paths,
                level_arr: ruleForm.level_data,
                order_by: ruleForm.sort,
            }
            if (type == 2) {
                data.product_common_id = gid
                data.action = "update"
            }
            let url = type == 1 ? "product/common/add" : "product/common/update"
            proxy.$axios
                .post(url, data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        proxy.$message({ message: `${type == 1 ? "添加成功！" : "编辑成功！"}`, type: "success" })
                        // router.push("/Goods/GoodsPublic")
                        router.back(-1)
                    } else {
                        proxy.$message({ message: res.data.msg, type: "error" })
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
    img_paths.value = ""
}

/**
 * 商品等级
 * @param {Boolean} loading 加载
 * @param {Array} level_data 等级数组
 * @param {Function} clickLevelAdd 点击添加
 */
const loading = ref(false)
const clickLevelAdd = () => {
    ruleForm.level_data.push({
        level_id: "",
        weight: "",
        volume: "0",
    })
}
// 修改选中等级值操作
function changeVal() {
    let arr = []
    ruleForm.level_data.map((val) => {
        arr.push(val.level_id)
    })
    pub_options.value.leave_list.map((item) => {
        item.disabled = arr.indexOf(item.level_id) != -1
    })
}
// 删除
const clickDel = (row, index) => {
    // 添加
    if (type == 1) {
        ruleForm.level_data.splice(index, 1)
        changeVal()
        return
    }
    // 编辑时删除，当前数据有为空的时候前端删除，不对接接口
    for (let i in row) {
        if (row[i] == "") {
            ruleForm.level_data.splice(index, 1)
            changeVal()
            return
        }
    }
    // 编辑时才调用删除接口
    proxy.$axios
        .post("product/common/update", {
            action: "level_del",
            product_common_id: gid,
            level_id: row.level_id,
        })
        .then((res) => {
            if (res.data.code == 0) {
                ruleForm.level_data.splice(index, 1)
                changeVal()
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}
// 保存
const clickAdd = (row) => {
    for (let i in row) {
        if (row[i] == "") {
            proxy.$message({ message: "请完善等级信息", type: "warning" })
            return
        }
    }
    proxy.$axios
        .post("product/common/update", {
            action: "level_add",
            product_common_id: gid,
            level_id: row.level_id,
            weight: row.weight,
            volume: row.volume,
        })
        .then((res) => {
            if (res.data.code != 0) {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

/**
 * 添加图片
 * @property {Boolean} showImg 显示图片库
 * @property {Function} selectImg 选择图片
 */
const showImg = ref(false)
const srcList = ref([])
const selectImg = (val) => {
    showImg.value = false
    ruleForm.img_paths = val[0].photo
    srcList.value.push(proxy.imgUrl + val[0].photo)
}
const delImg = () => {
    ruleForm.img_paths = ""
    srcList.value = []
}

/**
 * 获取商品分类、颜色、等级、物流
 */
const pub_options = ref({})
function pubClass() {
    proxy.$axios
        .get("product/com")
        .then((res) => {
            if (res.data.code == 0) {
                pub_options.value = res.data.data
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}
</script>
<script>
export default {
    name: "GoodsPublicUpdate",
}
</script>

<style lang="less" scoped>
.level-table {
    width: 100%;
    margin: 14px 0px;

    :deep(.el-select) {
        .el-input {
            width: 240px;
        }
    }
}
</style>
